import os
import logging

import handler_lib
from assess import assess
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

''' Fetches a URL, parses it, compares urls it extracts with the SB API.
'''

class Results(webapp.RequestHandler):
  '''Handles a /check request.'''
  def DisplayFindings(self, findings):
    '''Group findings by sort'''
    groups = {} # {name, []}
    results = [] # [name, items = {name, contents, src}]
    for finding in findings:
      if finding.sort not in groups:
        group = {'name': finding.sort, 'items': []}
        groups[finding.sort] = group
        results.append(group)        
      group = groups[finding.sort]
      group['items'].append({'name': finding.sort,
          'contents': finding.data, 'src': finding.url,
          'blacklisted': finding.url_blacklisted})

    return results

  def get(self):
    assessor = assess.Assessor()
    (assessment, findings) = assessor.Assess(self.request.get('url'))
    
    path = os.path.join(os.path.dirname(__file__), 'html/results.html')
    self.response.out.write(template.render(path,
        {'url': assessment.url, 'blacklisted': assessment.top_blacklisted,
         'source': assessment.response_body,
         'errors': [], 'findings': self.DisplayFindings(findings),
         'userdata': handler_lib.GetUserData()}))


